package com.xinghanlaser.applet.scheduled;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xinghanlaser.applet.entity.DealerSecretKey;
import com.xinghanlaser.applet.mapper.DeliveryMapper;
import com.xinghanlaser.applet.service.IDealerSecretService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *
 * <p>
 *
 * @author: mftuo 陀铭峰
 * @since: 2024/5/27 13:34
 */
@Component
@Slf4j
public class AutoDealerSecretKey {

    @Resource
    private IDealerSecretService dealerSecretService;

    @Resource
    private DeliveryMapper deliveryMapper;

    @Scheduled(fixedDelay = 600000)
    public void doSomethingEveryMinuteWithCron() {
        log.info("===【自动生成经销商密钥 定时任务 开始】===");

        // 查询当前已经插入的经销商
        Set<String> existDealerName = dealerSecretService.list(Wrappers.lambdaQuery(new DealerSecretKey())
                        .select(DealerSecretKey::getId, DealerSecretKey::getDealerName)
                )
                .stream()
                .map(DealerSecretKey::getDealerName)
                .collect(Collectors.toSet());

        // 查询所有的经销商
        Set<String> allDealerName = deliveryMapper.getAllDealerName();

        // 计算还没有插入的经销商
        Set<DealerSecretKey> insertEntity = allDealerName.stream()
                .filter(item -> !existDealerName.contains(item))
                .map(item -> {
                    DealerSecretKey entity = new DealerSecretKey();
                    entity.setDealerName(item);
                    entity.setSecretKey(item);
                    return entity;
                }).collect(Collectors.toSet());

        // 插入数据
        if(!insertEntity.isEmpty()){
            dealerSecretService.saveBatch(insertEntity);
        }

        log.info("===【自动生成经销商密钥 定时任务 结束】===");
    }
}
